package emulator.hardware.clock;

import java.util.Observable;

public class TickScales extends Observable {
	private long counting_interval = 1000000;
	private long start_time;
	private long clock_speed = 0;
	private long last_trigger;
	private long next_trigger;

	public void init() {
		start_time = System.nanoTime();
		advanceTriggerFrom(0);
	}

	private void advanceTriggerFrom(long ticks) {
		last_trigger = ticks;
		next_trigger = last_trigger + counting_interval;
	}

	public void measureTicks(long ticks) {
		if (ticks >= next_trigger)
		{
			long now = System.nanoTime();
			long elapsed = now - start_time;
			start_time = now;
			setClockSpeed((long)((ticks-last_trigger)*1e9 / elapsed));
			advanceTriggerFrom(ticks);
		}
	}

	public void setClockSpeed(long clock_speed) {
		this.clock_speed = clock_speed;
		setChanged();
		notifyObservers(clock_speed);
	}

	public long getClockSpeed() {
		return clock_speed;
	}
}